package com.guldan.jaina.task;

import com.alibaba.fastjson.JSON;
import com.guldan.core.constants.CommonConstant;
import com.guldan.core.redis.CacheService;
import com.guldan.jaina.dto.dicType.DicTypeDTO;
import com.guldan.jaina.dto.dicType.DicTypeSearchDTO;
import com.guldan.jaina.dto.dictionary.DictionaryDTO;
import com.guldan.jaina.dto.dictionary.DictionarySearchDTO;
import com.guldan.jaina.manager.DicTypeManager;
import com.guldan.jaina.manager.DictionaryManager;
import com.guldan.jaina.utils.ComUtils;
import com.guldan.mapper.db.entity.Area;
import com.guldan.mapper.db.entity.AreaExample;
import com.guldan.mapper.db.entity.Organization;
import com.guldan.mapper.db.entity.OrganizationExample;
import com.guldan.mapper.db.mapper.AreaMapperExt;
import com.guldan.mapper.db.mapper.OrganizationMapperExt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Silas.
 * Date: 2017/1/6
 * Time: 10:53
 */
@Component
public class SyncRedisDataHandler {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private AreaMapperExt areaMapperExt;

    @Autowired
    private OrganizationMapperExt organizationMapperExt;

    @Autowired
    private CacheService cacheService;

    public void handler() {
        long begin = System.currentTimeMillis();
        try {
            ComUtils.init();

            SyncAreaIdData();
            logger.info("SyncAreaIdData.cost=" + (System.currentTimeMillis() - begin));
            begin = System.currentTimeMillis();
            SyncOrgCodeData();
            logger.info("SyncOrgCodeData.cost=" + (System.currentTimeMillis() - begin));
            begin = System.currentTimeMillis();
            SyncOrgIdData();
            logger.info("SyncOrgIdData.cost=" + (System.currentTimeMillis() - begin));
            begin = System.currentTimeMillis();
            SyncDicData();
            logger.info("SyncDicData.cost=" + (System.currentTimeMillis() - begin));
            begin = System.currentTimeMillis();
            SyncAreaData();
            logger.info("SyncAreaData.cost=" + (System.currentTimeMillis() - begin));


        } catch (Exception ex) {
            logger.error(ex.getMessage());
            ex.printStackTrace();
        }

    }

    //同步区划实体信息
    public void SyncAreaData() {
        try {

            List<Area> list = areaMapperExt.selectByExample(new AreaExample());
            for (int i = 0; i < list.size(); i++) {
                cacheService.putCache(String.format(CommonConstant.KEY_AREA_DATA, list.get(i).getAreaId()), list.get(i));
                ComUtils.setAreaById(list.get(i).getAreaId(), list.get(i));
                logger.info(String.format(CommonConstant.KEY_AREA_DATA, list.get(i).getAreaId()));
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            ex.printStackTrace();
        }
    }

    //同步区划id
    private void SyncAreaIdData() {
        try {
            List<Integer> ids = getChildrenAreaIds(0);
            //cacheService.putCache(String.format(CommonConstant.KEY_AREA, 0), ids, 60 * 60 * 24 * 7);
            logger.info(JSON.toJSONString(ids));
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            ex.printStackTrace();
        }
    }

    private List<Integer> getChildrenAreaIds(Integer parentId) {
        List<Integer> list = new ArrayList<>();

        AreaExample example = new AreaExample();
        AreaExample.Criteria criteria = example.createCriteria();
        criteria.andAreaParentIdEqualTo(parentId);
        criteria.andIsDeleteEqualTo(false);

        List<Area> entityList = areaMapperExt.selectByExample(example);
        if (entityList != null && entityList.size() > 0) {
            for (Area entity : entityList) {

                list.add(entity.getAreaId());

                List<Integer> childs = getChildrenAreaIds(entity.getAreaId());

                cacheService.putCache(String.format(CommonConstant.KEY_AREA, entity.getAreaId()), childs, CommonConstant.TIME_SECOND_ONEWEEK);

                list.addAll(childs);
            }
        }
        return list;
    }
    //同步区划id end

    //同步机构code
    private void SyncOrgCodeData() {
        try {
            List<String> ids = getChildrenOrgCodes("-1");
            logger.info(JSON.toJSONString(ids));
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            ex.printStackTrace();
        }
    }

    private List<String> getChildrenOrgCodes(String parentCode) {
        List<String> list = new ArrayList<>();
        OrganizationExample example = new OrganizationExample();
        OrganizationExample.Criteria criteria = example.createCriteria();
        criteria.andOrgParentCodeEqualTo(parentCode);
        criteria.andIsDeleteEqualTo(false);
        List<Organization> entityList = organizationMapperExt.selectByExample(example);
        if (entityList != null && entityList.size() > 0) {
            for (Organization entity : entityList) {
                list.add(entity.getOrgCode());
                List<String> childs = getChildrenOrgCodes(entity.getOrgCode());
                cacheService.putCache(String.format(CommonConstant.KEY_ORG_CODE, entity.getOrgCode()), childs);
                list.addAll(childs);
            }
        }
        return list;
    }
    //同步机构code end

    //同步机构id
    private void SyncOrgIdData() {
        try {
            List<Integer> ids = getChildrenOrgIds(0);
            logger.info(JSON.toJSONString(ids));
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            ex.printStackTrace();
        }
    }

    private List<Integer> getChildrenOrgIds(Integer parentId) {
        List<Integer> list = new ArrayList<>();
        OrganizationExample example = new OrganizationExample();
        OrganizationExample.Criteria criteria = example.createCriteria();
        criteria.andOrgParentIdEqualTo(parentId);
        criteria.andIsDeleteEqualTo(false);
        List<Organization> entityList = organizationMapperExt.selectByExample(example);

        if (entityList != null && entityList.size() > 0) {
            for (Organization entity : entityList) {

                list.add(entity.getOrgId());

                List<Integer> childs = getChildrenOrgIds(entity.getOrgId());

                cacheService.putCache(String.format(CommonConstant.KEY_ORG, entity.getOrgId()), childs);

                list.addAll(childs);
            }
        }
        return list;
    }
    //同步机构id end

    @Autowired
    private DicTypeManager dicTypeManager;

    @Autowired
    private DictionaryManager dictionaryManager;

    //同步字典,key: dictypeid_diccode, value: dicvalue
    private int SyncDicData() {
        int count = 0;
        List<DicTypeDTO> dicTypeDTOList = dicTypeManager.all(new DicTypeSearchDTO());
        for (DicTypeDTO dicTypeDTO : dicTypeDTOList) {
            DictionarySearchDTO dictionarySearchDTO = new DictionarySearchDTO();
            dictionarySearchDTO.setDicTypeId(dicTypeDTO.getDicTypeId());
            List<DictionaryDTO> dictionaryDTOList = dictionaryManager.all(dictionarySearchDTO);
            if (dictionaryDTOList != null && dictionaryDTOList.size() > 0) {

                cacheService.putCache(String.format(CommonConstant.KEY_DIC_TYPE, dicTypeDTO.getDicTypeId()), dictionaryDTOList);
                if (ComUtils.dicMap.containsKey(dicTypeDTO.getDicTypeId())) {
                    ComUtils.dicMap.remove(dicTypeDTO.getDicTypeId());
                }
                ComUtils.dicMap.put(dicTypeDTO.getDicTypeId(), dictionaryDTOList);

                for (DictionaryDTO dictionaryDTO : dictionaryDTOList) {
                    try {
                        cacheService.putCache(String.format(CommonConstant.KEY_DIC, dicTypeDTO.getDicTypeId(), dictionaryDTO.getDictionaryCode()), dictionaryDTO);
                        count++;
                    } catch (Exception ex) {
                    }
                }
            }
        }
        logger.info("SyncDicData, success=" + count);
        return count;
    }


}
